package tech.aistar.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.aistar.config.AlipayConfig;
import tech.aistar.pojo.entity.Orders;
import tech.aistar.service.OrderService;
import tech.aistar.service.UserService;

import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("mm")
public class AlipayController2 {
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    @PostMapping("ms/{uid}/{orderNum}")
    public String alipayNotifyNotice(@PathVariable("uid") Integer uid, @PathVariable("orderNum") String orderNum, HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {

        // 获取支付宝 POST 过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

//        // 验证签名
//        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
//        if (!signVerified) {
//            // 签名错误，不处理
//            return "fail";
//        }
//
////         验证 app_id
//        if (!AlipayConfig.app_id.equals(params.get("app_id"))) {
//            // app_id 不一致，不处理
//            return "fail";
//        }
////
//////         验证交易状态
//        String tradeStatus = params.get("trade_status");
//        if (!"TRADE_SUCCESS".equals(tradeStatus) && !"TRADE_FINISHED".equals(tradeStatus)) {
//            // 交易状态不是成功或已完成，不处理
//
//            return "fail";
//        }

//         验证商户订单号
        String outTradeNo = params.get("out_trade_no");
//         根据商户订单号查询订单信息
        Orders order = orderService.seltonum(outTradeNo);

        if (order == null) {
            LocalDate now = LocalDate.now();
            String time = "";
            // 验证订单金额
            String totalAmount = params.get("total_amount");
            String vipname = "";
            int vipstatus = 0;
            int orderstatus = 0;
            if (totalAmount.equals("9.00")) {
                vipname = "普通会员月卡";
                vipstatus = 1;
                LocalDate dateAfter30Days = now.plusDays(30);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("88.00")) {
                vipname = "普通会员年卡";
                vipstatus = 2;
                LocalDate dateAfter30Days = now.plusDays(365);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("14.00")) {
                vipname = "超级会员月卡";
                vipstatus = 3;
                LocalDate dateAfter30Days = now.plusDays(30);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("118.00")) {
                vipname = "超级会员年卡";
                vipstatus = 4;
                LocalDate dateAfter30Days = now.plusDays(365);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("368.00")) {
                vipname = "永久会员";
                vipstatus = 5;
                LocalDate dateAfter30Days = now.plusDays(500);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            }
            if (null != totalAmount) {
                orderstatus = 1;
            } else {
                orderstatus = 0;
            }
//        if (!totalAmount.equals(order.getOrderprice())) {
//            // 订单金额不一致，不处理
//            return "fail";
//        }

            // 更新订单状态为已支付
            String nowtime = String.valueOf(new Date());

            orderService.ins(uid, orderNum, orderstatus, totalAmount,totalAmount, vipname, vipstatus, nowtime);
            userService.upvip(vipname, orderstatus, nowtime, time,uid);

            return "success";
        }else
        {
            // 获取当前日期
            LocalDate now = LocalDate.now();
            String time = "";
            // 验证订单金额
            String totalAmount = params.get("total_amount");
            String vipname = "";
            int vipstatus = 0;
            int orderstatus = 0;
            if (totalAmount.equals("9.00")) {
                vipname = "普通会员月卡";
                vipstatus = 1;
                LocalDate dateAfter30Days = now.plusDays(30);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("88.00")) {
                vipname = "普通会员年卡";
                vipstatus = 2;
                LocalDate dateAfter30Days = now.plusDays(365);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("14.00")) {
                vipname = "超级会员月卡";
                vipstatus = 3;
                LocalDate dateAfter30Days = now.plusDays(30);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("118.00")) {
                vipname = "超级会员年卡";
                vipstatus = 4;
                LocalDate dateAfter30Days = now.plusDays(365);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            } else if (totalAmount.equals("368.00")) {
                vipname = "永久会员";
                vipstatus = 5;
                LocalDate dateAfter30Days = now.plusDays(500);
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                time = dateAfter30Days.format(formatter);
            }
            if (null != totalAmount) {
                orderstatus = 1;
            } else {
                orderstatus = 0;
            }
//        if (!totalAmount.equals(order.getOrderprice())) {
//            // 订单金额不一致，不处理
//            return "fail";
//        }

            // 更新订单状态为已支付
            String nowtime = String.valueOf(new Date());

            orderService.updat(1, totalAmount, vipname, vipstatus, nowtime, outTradeNo);

            userService.upvip(vipname, orderstatus, nowtime, time,order.getUserid());
//         返回 success 表示处理成功
            return "success";
        }

    }
}
